import logging

from global_config import sql_two
from utils.decorators.cache import cache
from utils.decorators.check_sign import check_sign
from utils.decorators.request_limit import request_limit
from utils.exceptions import custom_abort
from utils.sql_helper import SQLHelper
from . import api


@api.route('/classTimetable/<string:class_name>', methods=['GET'])
@check_sign(set())
@request_limit()
@cache(set(), 120)
def handle_class_timetable(class_name: str):
    if not class_name:
        custom_abort(-6, '空关键词!')
    if len(class_name) < 5:
        custom_abort(-6, '班级号输入错误!')
    args = '%' + class_name + '%'
    timetable_items = []
    cnt = 0
    name_dict = {}
    for index, table in enumerate(SQLHelper.fetch_all(sql_two, args)):
        if table['课程名'] not in name_dict:
            name_dict[table['课程名']] = cnt
            cnt += 1
        timetable_items.append({
            'id': table.get('教学班编号', ''),
            'name': table.get('课程名', ''),
            'teacher': table.get('教师', ''),
            'weeks': table.get('周次', ''),
            'color': name_dict[table['课程名']],
            'dayOfWeek': table.get('星期', ''),
            'start': table.get('开始节次', ''),
            'length': table.get('时长节次', ''),
            'building': table.get('教学楼', ''),
            'classroom': table.get('教室', ''),
            'credit': table.get('学分', ''),
            'testType': table.get('考查方式', '')

        })
    if not timetable_items:
        custom_abort(-6, '没有此班级或已没有课程!')
    return {
        'code': 0,
        'data': timetable_items
    }


